package com.zmx.patients.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.giftedcat.easylib.selector.MultiImageSelector;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.NineGridAdapter;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.utils.AllUtil;
import com.zmx.patients.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class PersonalDataActivity extends BaseActivity {


    @BindView(R.id.goods_img)
    ImageView goodsImg;
    @BindView(R.id.text_name)
    TextView textName;
    @BindView(R.id.text_name0)
    TextView textName0;
    @BindView(R.id.text_name4)
    TextView textName4;
    @BindView(R.id.text_name1)
    TextView textName1;
    @BindView(R.id.text_name3)
    TextView textName3;
    @BindView(R.id.text_name5)
    TextView textName5;
    @BindView(R.id.text_name6)
    TextView textName6;
    @BindView(R.id.text_name7)
    TextView textName7;
    @BindView(R.id.relative0)
    RelativeLayout relative0;
    @BindView(R.id.relative1)
    RelativeLayout relative1;
    @BindView(R.id.relative4)
    RelativeLayout relative4;
    @BindView(R.id.relative2)
    RelativeLayout relative2;
    @BindView(R.id.relative3)
    RelativeLayout relative3;
    @BindView(R.id.relative5)
    RelativeLayout relative5;
    @BindView(R.id.relative6)
    RelativeLayout relative6;
    @BindView(R.id.relative7)
    RelativeLayout relative7;
    private String imagePath = "", s_msg;


    private RecyclerView rvImages;
    NineGridAdapter adapter;
    private int maxNum = 1;
    Unbinder unbinder;
    List<String> mSelect;
    List<String> select;//图片路径
    private static final int REQUEST_IMAGE = 2;

    private Integer is_idcard = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_data;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        textName0.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
        Glide.with(mActivity).load(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, "")).into(goodsImg);

        getUserInfo();

    }



    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 1:
                    Toast(s_msg);
                    Glide.with(mActivity).load(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, "")).into(goodsImg);
                    break;


                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONObject data = object.getJSONObject("data");
                        is_idcard = data.getInt("is_idcard");
                        textName.setText(data.getString("idcard"));
                        textName4.setText(data.getString("birthday"));
                        if (data.getInt("sex") == 1) {

                            textName1.setText("男");
                        } else {
                            textName1.setText("女");

                        }
                        textName5.setText(data.getString("weight") + "kg");
                        if (data.getInt("is_watch") == 0) {

                            textName6.setText("未绑定");
                        } else {
                            textName6.setText("绑定");

                        }
                        textName7.setText(data.getString("watch"));


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") ==1){

                            if (s_name.equals("name")){

                                MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.name,s_value);
                                textName0.setText(s_value);
                            }else if (s_name.equals("birthday")){

                                textName4.setText(s_value);

                            }else if (s_name.equals("sex")){

                                if (s_value.equals("1")){
                                    textName1.setText("男");
                                }else{
                                    textName1.setText("女");
                                }

                            }else if (s_name.equals("weight")){

                                textName5.setText(s_value);

                            }else if (s_name.equals("")){

                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 2:
                if (resultCode == RESULT_OK) {

                    select = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);

                    for (String s : select) {

                        if (s != "") {
                            imagePath = s;
                        }
                    }

                    upload();
                }
                break;
        }

    }


    private void upload() {// selImageList 包含图片路径的list


        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件


        File file = new File(imagePath); //根据路径创建file对象
        builder.addFormDataPart("image[]", //
                file.getName(),
                RequestBody.create(MediaType.parse("image/jpeg"), file)
        );

        builder.addFormDataPart("sign", AllUtil.md5(sing(null)));
        builder.addFormDataPart("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        builder.addFormDataPart("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        builder.addFormDataPart("ts", System.currentTimeMillis() / 1000 + "");
        builder.addFormDataPart("cmd", "editAvatar");
        builder.addFormDataPart("data[]", "");

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/app")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());

                    Log.e("数据", "数据" + object.toString());
                    s_msg = object.getString("msg");
                    if (object.getString("code").equals("1")) {

                        MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.avatar, object.getString("data"));
                        handler.sendEmptyMessage(1);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }


    public void alert_label(String hint,String name,Integer type,Integer logo) {

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_edit, null);//这里必须是final的
        final EditText et = view.findViewById(R.id.editText);
        if (type == 0){

            et.setInputType(InputType.TYPE_CLASS_NUMBER);

        }
        et.setHint(hint);
        builder.setTitle(hint);

        final AlertDialog dialog = builder.create();
        dialog.setView(view);

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        });
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(et.getText().toString())) {

                    setUserInfo(name, et.getText().toString(),logo);
                    dialog.dismiss();

                } else {

                    Toast("非法输入!");

                }


            }
        });


    }



    public void getUserInfo() {

        List<String> l = new ArrayList<>();
        l.add(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        Log.e("854545", "'" + AllUtil.md5(sing(null)));
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getUserInfo");
        params.put("data[member_id]", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

    }

    private String s_name="";
    private String s_value="";
    public void setUserInfo(String name,String value,Integer logo) {

        this.s_name = name;
        this.s_value = value;

        List<String> l = new ArrayList<>();
        if (logo == 1){

            l.add(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
            l.add(value);

        }else{

            l.add(value);
            l.add(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));

        }

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setUserInfo");
        params.put("data[member_id]", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("data["+name+"]", value);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 3, 404);

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    private Calendar calendar = Calendar.getInstance(Locale.CHINA);
    @OnClick({R.id.goods_img,R.id.relative0, R.id.relative1, R.id.relative4, R.id.relative2, R.id.relative3, R.id.relative5, R.id.relative6, R.id.relative7})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.goods_img:

                MultiImageSelector selector = MultiImageSelector.create(mActivity);
                selector.showCamera(true);
                selector.count(maxNum);
                selector.multi();
                selector.origin(mSelect);
                selector.start(mActivity, REQUEST_IMAGE);

                break;

            case R.id.relative0:

                alert_label("输入姓名","name",1,1);

                break;
            case R.id.relative1:

                if (is_idcard == 1){

                    Toast("无法修改身份证！");
                    return;
                }

                alert_label("输入身份证号","idcard",0,0);

                break;
            case R.id.relative4:

//                showDatePickerDialog(this, 4, textName4, calendar);

                new DatePickerDialog(mActivity, onDateSetListener, mYear, mMonth, mDay).show();

                break;

            case R.id.relative2:
                showSexChooseDialog();
                break;
            case R.id.relative3:
                break;
            case R.id.relative5:
                alert_label("输入体重","weight",0,1);
                break;
            case R.id.relative6:
                break;
            case R.id.relative7:
                break;
        }
    }

    /**
     * 日期选择器对话框监听
     */
    Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);
    private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String days;
            if (mMonth + 1 < 10) {
                if (mDay < 10) {

                    days = new StringBuffer().append(mYear).append("").append("0").
                            append(mMonth + 1).append("").append("0").append(mDay).toString();

                } else {

                    days = new StringBuffer().append(mYear).append("").append("0").
                            append(mMonth + 1).append("").append(mDay).toString();
                }

            } else {

                if (mDay < 10) {

                    days = new StringBuffer().append(mYear).append("").
                            append(mMonth + 1).append("").append("0").append(mDay).toString();

                } else {

                    days = new StringBuffer().append(mYear).append("").
                            append(mMonth + 1).append("").append(mDay).toString();

                }

            }

            s_value = days;
            setUserInfo("birthday",s_value,2);

        }
    };


    /**
     * 日期选择
     *
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作

                s_value = year + "" + (monthOfYear + 1) + "" + dayOfMonth;
                setUserInfo("birthday",s_value,2);

            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();

    }

    private String[] sexArry = new String[]{"女", "男"};// 性别选择
    private void showSexChooseDialog() {
        AlertDialog.Builder builder3 = new AlertDialog.Builder(this);// 自定义对话框
        builder3.setSingleChoiceItems(sexArry, 0, new DialogInterface.OnClickListener() {// 2默认的选中

            @Override
            public void onClick(DialogInterface dialog, int which) {// which是被选中的位置

                if (sexArry[which].equals("男")){
                    setUserInfo("sex", "1",1);
                }else{
                    setUserInfo("sex", "2",1);
                }
                dialog.dismiss();
            }
        });
        builder3.show();// 让弹出框显示
    }

}
